<template>
  <div id="viewQuestionView">
    <a-row :gutter="[24, 24]">
      <a-col :md="12" :xs="24">
        <a-tabs default-active-key="question" @change="handleTabChange">
          <a-tab-pane key="question" title="题目">
            <a-card v-if="question" :title="question.title">
              <a-descriptions
                title="判题条件"
                :column="{ xs: 1, md: 2, lg: 3 }"
              >
                <a-descriptions-item label="时间限制">
                  {{ question.judgeConfig.timeLimit ?? 0 }} ms
                </a-descriptions-item>
                <a-descriptions-item label="内存限制">
                  {{ question.judgeConfig.memoryLimit ?? 0 }} KB
                </a-descriptions-item>
                <a-descriptions-item label="堆栈限制">
                  {{ question.judgeConfig.stackLimit ?? 0 }} KB
                </a-descriptions-item>
              </a-descriptions>
              <MdViewer :value="question.content || ''" />
              <template #extra>
                <a-space wrap>
                  <a-tag
                    v-for="(tag, index) of question.tags"
                    :key="index"
                    color="green"
                    >{{ tag }}
                  </a-tag>
                </a-space>
              </template>
            </a-card>
          </a-tab-pane>
          <a-tab-pane key="answer" title="答案">
            <a-spin :spinning="loadingAnswer">
              <div v-if="answerContent" class="answer-content">
                <MdViewer :value="answerContent || ''" />
              </div>
              <div v-else-if="errorMessage" class="error-message">
                {{ errorMessage }}
              </div>
            </a-spin>
          </a-tab-pane>
        </a-tabs>
      </a-col>
      <a-col :md="12" :xs="24">
        <a-form :model="form" layout="inline">
          <a-form-item
            field="language"
            label="编程语言"
            style="min-width: 240px"
          >
            <a-select
              v-model="form.language"
              :style="{ width: '320px' }"
              placeholder="选择编程语言"
            >
              <a-option>java</a-option>
              <a-option>python</a-option>
              <a-option>cpp</a-option>
              <a-option>javascript</a-option>
              <a-option>go</a-option>
            </a-select>
          </a-form-item>
        </a-form>
        <CodeEditor
          :value="form.code as string"
          :language="form.language"
          :handle-change="changeCode"
        />
        <a-divider size="0" />
        <!-- 提交按钮（保持之前的绿色样式） -->
        <a-button class="custom-submit-btn" @click="doSubmit">
          提交代码
        </a-button>
      </a-col>
    </a-row>
  </div>
</template>

<script setup lang="ts">
import { onMounted, ref, watchEffect, withDefaults, defineProps } from "vue";
import message from "@arco-design/web-vue/es/message";
import CodeEditor from "@/components/CodeEditor.vue";
import MdViewer from "@/components/MdViewer.vue";
import {
  QuestionControllerService,
  QuestionSubmitAddRequest,
  QuestionVO,
} from "../../../generated";

interface Props {
  id: string;
}

const props = withDefaults(defineProps<Props>(), {
  id: () => "",
});

const question = ref<QuestionVO>();
const answerContent = ref<string>(""); // 直接存储答案内容字符串
const loadingAnswer = ref(false);
const errorMessage = ref("");

const loadData = async () => {
  const res = await QuestionControllerService.getQuestionVoByIdUsingGet(
    props.id as any
  );
  if (res.code === 0) {
    question.value = res.data;
  } else {
    message.error("加载失败，" + res.message);
  }
};

// 加载答案的函数 - 使用QuestionVO获取答案内容
const loadAnswer = async () => {
  if (!props.id) return;

  loadingAnswer.value = true;
  errorMessage.value = "";
  answerContent.value = "";

  try {
    // 调用获取题目详情的接口，从QuestionVO中读取答案内容
    const res = await QuestionControllerService.getQuestionVoByIdUsingGet(
      Number(props.id)
    );
    if (res.code === 0 && res.data) {
      // 假设答案内容存储在QuestionVO的answer字段中
      // 这里根据实际后端字段名调整，可能是answer、solution等
      answerContent.value = res.data.answer || "";

      // 如果没有答案内容，显示提示
      if (!answerContent.value) {
        errorMessage.value = "该题目暂无答案解析";
      }
    } else {
      errorMessage.value = "获取答案失败: " + res.message;
    }
  } catch (error) {
    console.error("获取答案异常:", error);
    errorMessage.value = "获取答案异常，请稍后再试";
  } finally {
    loadingAnswer.value = false;
  }
};

// 标签页切换处理
const handleTabChange = (activeKey: string) => {
  if (activeKey === "answer") {
    loadAnswer();
  }
};

// 设置Java默认代码模板
const defaultJavaCode = `public class Main {
    public static void main(String[] args) {

    }
}`;

// 设置不同语言的默认代码
const getDefaultCodeByLanguage = (language: string) => {
  switch (language) {
    case "java":
      return defaultJavaCode;
    case "python":
      return 'print("Hello, World!")\n';
    case "cpp":
      return '#include <iostream>\n\nint main() {\n    std::cout << "Hello, World!" << std::endl;\n    return 0;\n}\n';
    case "javascript":
      return 'console.log("Hello, World!");\n';
    case "go":
      return 'package main\n\nimport "fmt"\n\nfunc main() {\n    fmt.Println("Hello, World!")\n}\n';
    default:
      return "";
  }
};

const form = ref<QuestionSubmitAddRequest>({
  language: "java",
  code: getDefaultCodeByLanguage("java"),
});

/**
 * 提交代码
 */
const doSubmit = async () => {
  if (!question.value?.id) {
    return;
  }

  const res = await QuestionControllerService.doQuestionSubmitUsingPost({
    ...form.value,
    questionId: question.value.id,
  });
  if (res.code === 0) {
    message.success("提交成功");
  } else {
    message.error("提交失败," + res.message);
  }
};

/**
 * 页面加载时，请求数据
 */
onMounted(() => {
  loadData();
});

const changeCode = (value: string) => {
  form.value.code = value;
};
</script>

<style>
#viewQuestionView {
  max-width: 1400px;
  margin: 0 auto;
}

#viewQuestionView .arco-space-horizontal .arco-space-item {
  margin-bottom: 0 !important;
}

/* 提交按钮样式（保持之前的绿色样式） */
.custom-submit-btn {
  background-color: white !important;
  color: #2ecc71 !important;
  border: 2px solid #2ecc71 !important;
  border-radius: 8px !important;
  min-width: 200px !important;
  height: 40px !important;
  font-weight: 500 !important;
  font-size: 14px !important;
  transition: all 0.3s !important;
}

.custom-submit-btn:hover {
  background-color: #2ecc71 !important;
  color: white !important;
}

/* 修改标签页激活状态颜色为绿色 */
#viewQuestionView .arco-tabs-tab-active {
  color: #2ecc71 !important;
}

#viewQuestionView .arco-tabs-ink-bar {
  background-color: #2ecc71 !important;
}

#viewQuestionView .arco-tabs-tab:hover:not(.arco-tabs-tab-disabled) {
  color: #2ecc71 !important;
}

.answer-content {
  padding: 16px;
  border-radius: 8px;
  background-color: #f9fafb;
  margin-top: 12px;
}

.error-message,
.empty-message {
  padding: 16px;
  text-align: center;
  color: #f5222d;
}

.empty-message {
  color: #666;
}
</style>
